package com.interactive.internal.ant;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import junit.extensions.abbot.ScriptFixture;
import junit.extensions.abbot.TestHelper;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

public class AbbotTestFixture extends ScriptFixture
{
  public AbbotTestFixture(String filename)
  {
    super(filename);
  }

  public static Test suite()
  {
    String homeDir = System.getProperty("AbbotTestFixture.scriptHome");
    if (homeDir != null)
    {
      File homeFile = new File(homeDir);
      if (checkHomeDirectory(homeFile))
      {
        List files = AbbotTestSuite.findTestScripts(homeFile);
        removeNonAbbotFiles(files);
        if (files.size() > 0)
        {
          return new AbbotTestSuite(AbbotTestFixture.class,
              toStringArray(files));
        }
      }
    }
    TestSuite suite = new TestSuite();
    suite.addTest(new EmptyTestCase());
    return suite;
  }

  static boolean checkHomeDirectory(File homeFile)
  {
    if (homeFile.isDirectory())
    {
      File[] children = homeFile.listFiles();
      for (int i = 0; i < children.length; i++)
      {
        if (checkHomeDirectory(children[i]))
          return true;
      }
    }
    return homeFile.exists() && acceptFile(homeFile.getAbsolutePath());
  }

  static void removeNonAbbotFiles(List files)
  {
    for (Iterator i = files.iterator(); i.hasNext();)
    {
      if (!AbbotTestSuite.acceptFile(i.next().toString()))
        i.remove();
    }
  }

  private static String[] toStringArray(List files)
  {
    String[] strArray = new String[files.size()];
    for (int i = 0; i < strArray.length; i++)
    {
      strArray[i] = files.get(i).toString();
    }
    return strArray;
  }

  public static void main(String[] args)
  {
    TestHelper.runTests(args, AbbotTestFixture.class);
  }

  public static class EmptyTestCase extends TestCase
  {
    public EmptyTestCase()
    {
      super("testNoAbbotScripts");
    }

    public void testNoAbbotScripts()
    {
    }
  }

  public static boolean acceptFile(String filename)
  {
    return filename.endsWith(".abbot");
  }
}
